package com.example.icampusevent;

import com.example.icampusevent.jsonobjects.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.readystatesoftware.viewbadger.BadgeView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EventDetailActivity extends Activity {
	
	private EventDetail detail = null;
	private long eventId;
	private String userId; 
	private int mode;
	
	private final int CHECKIN = 0;
	private final int CHECKOUT = 1;
	
	private BadgeView badge;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_detail);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        
        Intent intent = getIntent();
        this.eventId= intent.getLongExtra("EVENTID", 0);
        this.userId = intent.getStringExtra("USERID");
        this.mode = intent.getIntExtra("MODE", CHECKIN);
        
        Button msgButton = (Button)findViewById(R.id.go_message_button);
	    badge = new BadgeView(EventDetailActivity.this, msgButton);
    }
    
    @Override 
    public void onResume() {
    	
    	super.onResume();
    	
    	// Get event detail from server
        Intent intent = getIntent();
        this.eventId= intent.getLongExtra("EVENTID", 0);
        this.userId = intent.getStringExtra("USERID");
        this.mode = intent.getIntExtra("MODE", CHECKIN);
        
        LoadEventDetailTask task = new LoadEventDetailTask();
        String url = "http://hamedaan.usc.edu:8080/team15/EventServlet?q=detail&eventid=" + Long.toString(eventId);
        task.execute(url);
        
        // Initialize buttons
        if(this.mode == CHECKIN) {
        	final Button checkoutButton = (Button)findViewById(R.id.checkout_button);
        	checkoutButton.setBackgroundResource(R.drawable.login_button_shape_pressed);
        	checkoutButton.setClickable(false);
        	
        	final Button directionButton = (Button) findViewById(R.id.get_direction_button);
        	directionButton.setBackgroundResource(R.drawable.login_button_selector);
        	directionButton.setClickable(true);
            directionButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(EventDetailActivity.this, CampusMapActivity.class);
                    intent.putExtra("LAN", detail.getLat());
            		intent.putExtra("LNG", detail.getLng());
                    startActivity(intent);
                }
            });
            
            final Button checkinButton = (Button) findViewById(R.id.checkin_button);
            checkinButton.setClickable(true);
            checkinButton.setBackgroundResource(R.drawable.login_button_selector);
            checkinButton.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				Intent intent = new Intent(EventDetailActivity.this, CheckinActivity.class);
    				intent.putExtra("EVENTID", eventId);
    				intent.putExtra("USERID", userId);
                    startActivity(intent);
    			}
    		});
        }
        else {
        	final Button checkoutButton = (Button)findViewById(R.id.checkout_button);
        	checkoutButton.setClickable(true);
        	checkoutButton.setBackgroundResource(R.drawable.login_button_selector);
        	checkoutButton.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View v) {
        			String url = "http://hamedaan.usc.edu:8080/team15/InviteServlet?q=checkout&eventid=" + eventId +
        					"&userid=" + userId;
        			CheckOutTask task = new CheckOutTask();
        			task.execute(url);
        		}
        	});
        	
        	final Button directionButton = (Button) findViewById(R.id.get_direction_button);
        	directionButton.setBackgroundResource(R.drawable.login_button_shape_pressed);
        	directionButton.setClickable(false);
            
            final Button checkinButton = (Button) findViewById(R.id.checkin_button);
            checkinButton.setBackgroundResource(R.drawable.login_button_shape_pressed);
            checkinButton.setClickable(false);
        }
        
        // Set OnclickListeners for buttons
        setButtons();
        
        // Set message notifications
    	setNotification();
    }
    
    @Override
    public void onNewIntent (Intent intent) {
    	setIntent(intent);
    }
    
    private void setButtons() {
    	
    	// set up customized action bar
    	Button homeButton = (Button)findViewById(R.id.go_home_button);
    	homeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(EventDetailActivity.this, MainActivity.class);
				intent.putExtra("USERID", userId);
				startActivity(intent);
			}
    	});
    	
    	
    	Button searchButton = (Button)findViewById(R.id.go_search_button);
    	searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// start the search activity
	    		Intent searchIntent = new Intent(EventDetailActivity.this, SearchActivity.class);
	    		searchIntent.putExtra("USERID", userId);
	    		startActivity(searchIntent);
			}
    	});
    	
    	Button friendButton = (Button)findViewById(R.id.go_friend_button);
    	friendButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// start friend viewing activity
				Intent friendIntent = new Intent(EventDetailActivity.this, FriendActivity.class);
	    		friendIntent.putExtra("USERID", userId);
	    		startActivity(friendIntent);
			}
    	});
    	
    	Button messageButton = (Button)findViewById(R.id.go_message_button);
    	messageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent msgIntent = new Intent(EventDetailActivity.this, MessageActivity.class);
	    		msgIntent.putExtra("USERID", userId);
	    		startActivity(msgIntent);
			}
    	});
    }
    
    
    private void setNotification() {
    	String url = "http://hamedaan.usc.edu:8080/team15/AlertServlet?q=count&userid=" + this.userId;
    	GetMessageNumberTask task = new GetMessageNumberTask();
    	task.execute(url);
    }
    
    private class GetMessageNumberTask extends AsyncTask<String, Integer, Reader> {
	     protected Reader doInBackground(String... url) {
	    	 InputStream source = retrieveStream(url[0]);
	 		 if(source == null) return null;
	 		 
	 		 Reader inputReader = new InputStreamReader(source);
	 		 return inputReader;
	     }

	     protected void onPostExecute(Reader json) {
	 		 Gson gson = new Gson();
			 ReturnStatus status = gson.fromJson(json, ReturnStatus.class);

			 int num = Integer.parseInt(status.getStatus());
			 if(num == -1) {
				 toast("Error: cannot get messages number.");
			 }
			 else if(num == 0) {
				 badge.hide();
			 }
			 else {
			     badge.setText(Integer.toString(num));
			     badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			     badge.show();
			 }
			 
	     }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		
	 		return null;
	 	}
	}
    
    
    private class CheckOutTask extends AsyncTask<String, Integer, Reader> {
	     protected Reader doInBackground(String... url) {
	    	 InputStream source = retrieveStream(url[0]);
	 		 if(source == null) return null;
	 		 
	 		 Reader inputReader = new InputStreamReader(source);
	 		 return inputReader;
	     }

	     protected void onPostExecute(Reader json) {
	 		 Gson gson = new Gson();
			 ReturnStatus status = gson.fromJson(json, ReturnStatus.class);
			 if(status.getStatus().equals("error")) {
				 toast("Error: cannot check out.");
			 }
			 else {
				 toast("Check out succesfully!");
				 
				 // Navigate back to main activity
				 Intent intent = new Intent(EventDetailActivity.this, MainActivity.class);
				 intent.putExtra("USERID", userId);
				 startActivity(intent);
			 }
	     }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		
	 		return null;
	 	}
	}
   
    
    private class LoadEventDetailTask extends AsyncTask<String, Integer, Reader> {
	     protected Reader doInBackground(String... url) {
	    	 InputStream source = retrieveStream(url[0]);
	 		 if(source == null) return null;
	 		 
	 		 Reader inputReader = new InputStreamReader(source);
	 		 return inputReader;
	     }

	     protected void onPostExecute(Reader json) {
	 		 Gson gson = new Gson();
			 detail = gson.fromJson(json, EventDetail.class);
			 
			 // Populate the detail table on UI
			 TextView title = (TextView)findViewById(R.id.event_title_text_view);
			 title.setText(detail.getTitle());
			 TextView category = (TextView)findViewById(R.id.event_category_text_view);
			 category.setText(detail.getCategory());
			 TextView location = (TextView)findViewById(R.id.event_location_text_view);
			 location.setText(detail.getBuildingName());
			 TextView summary = (TextView)findViewById(R.id.event_summary_text_view);
			 summary.setText(detail.getSummary());
			 TextView time = (TextView)findViewById(R.id.event_time_text_view);
			 time.setText(detail.getStart() + " - " + detail.getEnd());
	     }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		
	 		return null;
	 	}
	}
    
    public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(this, text, duration);
		toast.show();
	}
    
    
    public long getEventId() {
    	return this.eventId;
    }
    
    public String getUserId() {
    	return this.userId;
    }
}
